package com.banksoft.front.controller;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.bean.PaySetting;
import com.banksoft.admin.dao.OrderDao;
import com.banksoft.admin.dao.ProductDao;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.Product;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.bean.MessageUtil;
import com.banksoft.front.bean.ProductBean;
import com.banksoft.front.bean.TyNoticeSj;
import com.banksoft.front.util.WeixinUtil;
import com.banksoft.util.DateUtil;
import com.banksoft.util.QrCodeUtil;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * Created by vanjoger on 2017/1/2.
 */
@Controller
@RequestMapping("/front/order")
public class FrontOrderController extends BaseController {

    @Autowired
    OrderService orderService;
    @Autowired
    BaseService baseService;
    @Autowired
    UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(FrontProductController.class);

    @RequestMapping("pre")
    public String pre(Model model, String ids, HttpServletRequest request){
        List<ProductBean> data = new ArrayList<>();
        String totalMoney = "";
        if(StringUtil.isNotNull(ids)){
            String[] arrays = ids.split(",");
            for(String array:arrays){
                String[] idnum = array.split("-");
                if(idnum!=null&&idnum.length>1){
                    String id = idnum[0];
                    String num = idnum[1];
                    Product product = this.baseService.findById(ProductDao.class,id);
                    if(product!=null){
                        ProductBean bean = new ProductBean();
                        bean.setId(product.getId());
                        bean.setName(product.getName());
                        String images = product.getImages();
                        String image = "";
                        if(StringUtil.isNotNull(images)){
                            image = images.split("\\|")[0];
                        }
                        bean.setImage(image);
                        bean.setNum(num);
                        bean.setPrice(product.getPrice());
                        bean.setTotalPrice(StringNumber.mul(product.getPrice(),num));
                        data.add(bean);
                        totalMoney = StringNumber.add(totalMoney,bean.getTotalPrice());
                    }
                }
            }
        }
        model.addAttribute("data",data);
        model.addAttribute("totalMoney",totalMoney);
        return "front/order_pre";
    }

    @RequestMapping("save")
    public String save(Model model, String ids, String hidden_userName,String hidden_telephone,String hidden_province,String hidden_province_name,
                       String hidden_city,String hidden_city_name,String hidden_area,String hidden_area_name,
                       String hidden_address,String hidden_remark,String bonus_amount,String post_amount,HttpServletRequest request){
        try{
           /*  String openId = getCookie(SystemCache.SESSION_USER, request);
            User user  = this.userService.findByOpenId(openId);*/
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);

            Order order = this.orderService.save(user.getId(),ids,hidden_userName,hidden_telephone,hidden_province,hidden_province_name,
                    hidden_city,hidden_city_name,hidden_area,hidden_area_name,hidden_address,hidden_remark,bonus_amount,post_amount);


            model.addAttribute("orderId",order.getId());
            model.addAttribute("suc",true);
            if(order.getStatus().equals(OrderStatus.Pay.name())) {
               // model.addAttribute("suc",false);
               // model.addAttribute("msg","订单已提交成功");
                return "redirect:/front/user/order/detail?id="+order.getId();
            }
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","订单提交失败");
            model.addAttribute("suc",false);
        }
        return "front/order_getAuth";
    }


    /**
     * 获取相关订单信息   拿到微信支付凭证
     * @param orderId
     * @param request
     * @return
     */
    @RequestMapping(value="/getAuthentication",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getAuthentication(String orderId, HttpServletRequest request){
        try {
            logger.info(new Date()+"    ----开始微信支付----  "+orderId);
            //检查订单状态
            Order order = this.baseService.findById(OrderDao.class,orderId);
            if(order==null)
                return this.FmtResult(false,"未找到订单！",null);
            if(order.getStatus().equals(OrderStatus.Pay.name()))
                return this.FmtResult(false,"该订单已成功支付，无需再次支付！",null);
            //获取微信设置
            PaySetting paySetting = SystemCache.getPaySetting();

            String backUrl = "http://boaishangcheng.com/front/order/toPay";
                    //getDomain(request)+"/front/order/toPay";
            String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+paySetting.getAccountNo()
                    +"&redirect_uri=" + backUrl + "&response_type=code&scope=snsapi_base"+
                    "&state="+order.getId()+"#wechat_redirect";
            logger.info(" redirectUrl ------   "+redirectUrl);
            return this.FmtResult(true,"",redirectUrl);
        } catch (Exception e) {
            logger.error("获取凭证失败！", e);
            return this.FmtResult(false,"获取授权认证失败："+e.getMessage(),null);
        }
    }

    @RequestMapping("/toPay")
    public String toPay(String state,String code,Model model){
        model.addAttribute("state",state);
        model.addAttribute("code",code);
        return "front/order_pay";
    }

    /**
     * 获取用户认证 支付
     * @param orderId
     * @param code
     * @param request
     * @return
     */
    @RequestMapping("/pay")
    @ResponseBody
    public JSONObject pay(String orderId,String code,HttpServletRequest request){
        PaySetting setting = SystemCache.getPaySetting();

        String openId = WeixinUtil.getOpenId(setting, code);
        logger.info(new Date() + "  获取用户认证信息 ------  " + openId);
        if(openId == null){
            return this.FmtResult(false,"获取用户认证信息失败",null);
        }
        Order order = this.baseService.findById(OrderDao.class,orderId);
        try {

            String jsonStr = WeixinUtil.submitJson(setting, request, openId, order);
            logger.info("同意支付：" + jsonStr);
            if(jsonStr != null){
                return this.FmtResult(true,null,jsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(orderId+"   --支付失败 --- "+e);
            return this.FmtResult(false,"支付异常："+e.getMessage(),null);
        }
        //ew ErrorTip(1));
        return null;

    }

    /**
     * 微信支付结果  页面通知
     * @param orderId
     * @param errorMessage
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/payResultBack")
    public String payResultBack(String orderId, String errorMessage, HttpServletRequest request, HttpServletResponse response, Model model){
        String status = "fail";
        model.addAttribute("msg","支付失败");
        logger.info("微信移动端支付页面通知：：：支付结果 -- " + orderId + "   :    " + errorMessage);
        if("get_brand_wcpay_request:ok".equals(errorMessage)){
            status = "suc";
            model.addAttribute("msg","支付成功");
        }

        model.addAttribute("orderId",orderId);
        return "front/payback_result";
    }

    /**
     * 微信支付结果底层通知
     * @param request
     * @return
     */
    @RequestMapping("payNotifyResult")
    @ResponseBody
    public String payNotifyResult(HttpServletRequest request){
        String orderId = "";
        try {
            request.setCharacterEncoding("UTF-8");
            Map<String, String> requestMap = MessageUtil.parseXml(request);

            PaySetting setting = SystemCache.getPaySetting();
            String key = setting.getPayKey();
            logger.info("接收到结果：：" + requestMap);
            Object[] objects = (Object[]) WeixinUtil.notify(requestMap, key);
            String respMessage = "";
            TyNoticeSj returnTyNoticeSj = null;
            returnTyNoticeSj = (TyNoticeSj) objects[0];
            respMessage = (String) objects[1];
            orderId = (String) objects[2];
            logger.info("*******  微信手机端底层通知结果 ------  "+orderId+"  : "+returnTyNoticeSj.getResult_code());
            //找到订单
            logger.info("订单支付状态::;"+returnTyNoticeSj.getReturn_code()+" : "+returnTyNoticeSj.getReturn_msg()+" : "+("SUCCESS".equals(returnTyNoticeSj.getReturn_code())));
            if ("SUCCESS".equals(returnTyNoticeSj.getReturn_code())) {  //
                this.orderService.updateOrder(orderId,OrderStatus.Pay.name());
            }else{
                this.orderService.updateOrder(orderId,OrderStatus.Fail.name());
            }
            return respMessage;
        }catch (Exception e){
            e.printStackTrace();
            logger.info(orderId + "  *********** 微信手机端底层  " + e);
        }
        return null;
    }

    @RequestMapping("/cancel")
    @ResponseBody
    public JSONObject cancel(String orderId){
        try{
            this.orderService.cancelOrder(orderId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(true,null,null);
    }

}
